import {acceptFriendRequest, deleteFriend, sendFriendRequestTo} from '@/api/friend'
import { useFriendStore } from '@/stores/friendStore'
import { useSocket } from '@/socket'
import { userStore } from "@/stores/userStore.js";


export const friendService = () => {
    const socket = useSocket()
    const acceptRequestAndSync = async (requestInfo) => {
        const res = await acceptFriendRequest(requestInfo.receiver_id, requestInfo.sender_id)
        if (res.status === 200) {
            const friendStore = useFriendStore()
            friendStore.addFriend({
                id: requestInfo.sender_id,
                name: requestInfo.sender_name,
                pfp: requestInfo.sender_avatar,
                isOnline: true
            })

            socket.emit('friendAccepted', {
                accepter: {
                    id: userStore().userInfo.id,
                    name: userStore().userInfo.name,
                    pfp: userStore().userInfo.avatar,
                    isOnline: true
                },
                targetUser: {
                    id: requestInfo.sender_id,
                    name: requestInfo.sender_name,
                    pfp: requestInfo.sender_avatar
                }
            })

            return true
        } else {
            return false
        }
    }

    const sendFriendRequest = async (receiver_id) => {
        const res = await sendFriendRequestTo(userStore().userInfo.id, receiver_id)
        if (res.status === 200) {
            socket.emit('sendFriendReq', {
                isAccept: 0,
                sender_id: userStore().userInfo.id,
                sender_avatar: userStore().userInfo.avatar,
                sender_name: userStore().userInfo.name,
                receiver_id: receiver_id,
                send_time: new Date()
            })
            return true
        } else {
            return false
        }
    }

    const deleteFriends = async (sender_id, receiver_id) => {
        const res = await deleteFriend(sender_id, receiver_id)
        if (res.status === 200) {

        }
        return void 0
    }

    return {
        acceptRequestAndSync,
        sendFriendRequest
    }
}

